<?php
// +----------------------------------------------------------------------
// | KITEGO-Admin「开箱即用」「人人全栈」
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.kitego.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed KITEGO并不是自由软件，未经许可不能去掉KITEGO相关版权
// +----------------------------------------------------------------------
// | Author: KITEGO Team <bd@kitego.cn>
// +----------------------------------------------------------------------

namespace app\adminapi\middleware;

use app\dao\setting\SystemAdminDao;
use app\dao\setting\SystemRoleDao;
use Exception;
use kitego\enum\ApiCodeEnum;
use kitego\traits\AdminAuthTrait;
use think\Request;

class AdminLoginMiddleware
{
    use AdminAuthTrait;

    /**
     * 后台登陆验证中间件
     * @throws Exception
     */
    public function handle(Request $request, \Closure $next)
    {
        // 无需鉴权的接口放行
        if ($request->invokeController->checkSafeAction()) {
            return $next($request);
        }

        // 判断接口是否免登录
        $token = $request->header(config('cookie.token_name', 'Authorization'));
        if (empty($token)) {
            abort(ApiCodeEnum::UNAUTHORIZED, '未授权访问');
        }

        $token = trim(ltrim($token, 'Bearer'));
        $adminInfo = getAdminJWT($token);
        if (
            empty($adminInfo) ||
            empty($adminInfo['adminId']) ||
            empty($adminInfo['adminNickname']) ||
            empty($adminInfo['adminAvatar']) ||
            empty($adminInfo['adminRole'])
        ) {
            abort(ApiCodeEnum::UNAUTHORIZED, '未授权访问');
        }

        // 管理员信息
        $request->adminId = $adminInfo['adminId'];
        $request->adminNickname = $adminInfo['adminNickname'];
        $request->adminAvatar = $adminInfo['adminAvatar'];
        $request->adminRole = $adminInfo['adminRole'];

        // 校验管理员信息
        $systemAdmin = app()->make(SystemAdminDao::class)->find($request->adminId);
        if (
            !$systemAdmin ||
            $systemAdmin['status'] == 2 ||
            $systemAdmin['delete_flag'] == 2 ||
            empty($systemAdmin['role_id'])
        ) {
            abort(ApiCodeEnum::UNAUTHORIZED, '未授权访问');
        }

        // 校验管理员角色信息
        $adminRoleIdArr = explode(',', $systemAdmin['role_id']);
        $roleWhere[] = ['id', 'in', $adminRoleIdArr];
        $roleWhere[] = ['status', '=', 1];
        $roleWhere[] = ['delete_flag', '=', 0];
        $adminRoleQuery = app()->make(SystemRoleDao::class)->getColumn($roleWhere, 'menu_ids, alias');
        if (empty($adminRoleQuery) || count($adminRoleQuery) != count($adminRoleIdArr)) {
            abort(ApiCodeEnum::UNAUTHORIZED, '未授权访问');
        }

        // 管理员角色ids
        $request->adminRoleId = $adminRoleIdArr;
        $request->adminRoleAlias = array_column($adminRoleQuery, 'alias');

        $adminRoleMenuIds = [];
        foreach ($adminRoleQuery as $va) {
            if (empty($adminRoleMenuIds)) {
                $adminRoleMenuIds = explode(',', $va['menu_ids']);
            } else {
                $adminRoleMenuIds = array_unique(array_merge($adminRoleMenuIds, explode(',', $va['menu_ids'])));
            }
        }
        $request->adminRoleMenuIds = $adminRoleMenuIds;

        return $next($request);
    }
}
